package cn.school.demo.ui.edit

import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentModifyPhoneBinding
import cn.school.demo.repository.DataRepository
import cn.school.demo.util.StringUtil
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.mylhyl.circledialog.CircleDialog

class ModifyPhoneFragment : Fragment() {
    private lateinit var viewModel: UpdatePhoneViewModel
    private lateinit var binding: FragmentModifyPhoneBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(UpdatePhoneViewModel::class.java)
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_modify_phone, container, false)
        binding.apply {
            lifecycleOwner = viewLifecycleOwner
            my = MyApplication.Companion
            vw = this@ModifyPhoneFragment
            vm = viewModel
        }
        return binding.root
    }

    fun gotoNext() {
        binding.fragmentModifyPhoneUpdateButton.isEnabled = false
        val text: String = when (viewModel.newPhone.value) {
            null -> "请输入手机号！"
            "" -> "请输入手机号！"
            else -> if (StringUtil.isMobilePhone(viewModel.newPhone.value!!)) "null"
            else "手机号输入不合法，请重新输入！"
        }
        if (text == "null") {
            viewModel.modifyVisible()
            getCode()
        } else {
            CircleDialog.Builder().setText(text).setNegative("确定", null)
                .show(parentFragmentManager)
        }
    }

    fun gotoBack() {
        when (viewModel.visibleOne.value) {
            View.VISIBLE -> MyApplication.goto(
                R.id.action_ModifyPhone_to_UpdatePhone,
                findNavController(),
                parentFragmentManager
            )
            View.GONE -> viewModel.modifyVisible()
        }
    }

    fun getCode() {
        viewModel.setGetCode(DataRepository().getCode(MyApplication.user!!.telephoneNumber))
        MyApplication.animationCountdown(
            binding.fragmentModifyPhoneGetCodeButton,
            MyApplication.animationCountdown["ModifyPhoneGetCode"],
            "ModifyPhoneGetCode"
        )
        viewModel.getCode.observe(viewLifecycleOwner) {
            //ToastUtils.showShort("验证码收到提醒！")
            LogUtils.d("验证码收到提醒！")
            binding.fragmentModifyPhoneUpdateButton.isEnabled = true
        }
    }

    fun update() {
        val text: String? = when (viewModel.code.value) {
            null -> "请输入验证码!"
            "" -> "请输入验证码!"
            else -> if (!StringUtil.isCode(viewModel.code.value.toString())) "验证码输入不合法！"
            else if (viewModel.code.value != viewModel.getCode.value) "验证码错误！"
            else null
        }
        if (!text.isNullOrEmpty()) {
            CircleDialog.Builder().setText(text).setNegative("确定", null)
                .show(parentFragmentManager)
        } else {
            //HTTP请求更新手机号
            LogUtils.d("更新步骤提醒！")
            val user = viewModel.user.value
            user!!.telephoneNumber = viewModel.newPhone.value!!
            viewModel.setUser(user)
            val isOk = DataRepository().editUserInfo(viewModel.user.value!!)
            isOk.observe(viewLifecycleOwner) {
                if (it.success) {
                    LogUtils.d("修改手机号成功！")
                    MyApplication.user = viewModel.user.value!!
                    CircleDialog.Builder().setText("修改手机号成功！").setNegative("确定") {
                        MyApplication.navigateThing["ModifyPhone"]?.let { n ->
                            MyApplication.goto(
                                n.toInt(),
                                findNavController(),
                                parentFragmentManager
                            )
                        } ?: MyApplication.goto(
                            R.id.action_ModifyPhone_to_Setting,
                            findNavController(),
                            parentFragmentManager
                        )
                    }
                        .show(parentFragmentManager)
                } else CircleDialog.Builder().setText(it.message).setTextColor(Color.RED)
                    .setNegative("确定", null).show(parentFragmentManager)
                //ToastUtils.showShort(it.message)
            }
        }
    }

    fun setNewPhone() = viewModel.setNewPhone(binding.fragmentModifyPhonePhoneEdit.text.toString())
    fun setCode() = viewModel.setCode(binding.fragmentModifyPhoneCodeText.text.toString())

}